package com.sample.lock.readWriteLock;

import java.io.*;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 在没有写操作的时候，允许多个线程同时读取共享资源；
 * 但是如果一个线程想去写这些共享资源，就不允许其他线程对该资源进行读和写的操作（读写，写写互斥）。
 * @author zg
 * @date 2021年3月30日
 */
public class PropertiesEditor {
	
	//读写锁
	private ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

	private static Properties properties;
	
	private static final String propFileName = "progress.properties";

	private String getPropFilePath(){
		//String currentDir = System.getProperty("user.dir");
		//return currentDir + File.separator + "read-write-lock" + File.separator + propFileName;
		return Paths.get("read-write-lock").toAbsolutePath() + File.separator + propFileName;
	}

	/**
	 * 加载文件
	 * @throws IOException
	 */
	public void load() throws IOException {
		properties = new Properties();
		try (FileInputStream fis = new FileInputStream(getPropFilePath())) {
			properties.load(fis);
		}
	}

	/**
	 * 设置属性
	 * @param key
	 * @param value
	 * @return
	 */
	private Boolean setProperty(String key, String value) {
		try (FileOutputStream fos = new FileOutputStream(getPropFilePath())) {
			if (properties == null) {
				load();
			}
			properties.setProperty(key, value);
			//保存
			properties.store(fos, "test");
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 修改
	 * @param key
	 * @param value
	 * @return
	 */
	public Boolean set(String key, String value) {
		boolean result = false;
		try {
			writeLock.lock();
			if (get(key) != null) {
				result = setProperty(key, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
            writeLock.unlock();
        }
		return result;
	}

	/**
	 * 新增
	 * @param key
	 * @param value
	 * @return
	 */
	public Boolean add(String key, String value) {
		boolean result = false;
		try {
			writeLock.lock();
			if (get(key) == null) {
				result = setProperty(key, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
            writeLock.unlock();
        }
		return result;
	}

	/**
	 * 获取属性值
	 * @param key
	 * @return
	 */
	public String get(String key) {
		try {
			readLock.lock();
			FileInputStream fis = new FileInputStream(getPropFilePath());
			if (properties == null) {
				load();
			}
			properties.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			readLock.unlock();
		}
		return properties.getProperty(key);
	}

	public static void main(String[] args) {
		PropertiesEditor pe = new PropertiesEditor();
		pe.add("name", "Jack");
		pe.set("key2", "fffff");

	}

}
